package cn.stylefeng.guns.modular.shuheng.controller;

import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.modular.shuheng.entity.Content;
import cn.stylefeng.guns.modular.shuheng.entity.Data;
import cn.stylefeng.guns.modular.shuheng.entity.Level;
import cn.stylefeng.guns.modular.shuheng.service.ContentService;
import cn.stylefeng.guns.modular.shuheng.service.DataService;
import cn.stylefeng.guns.modular.shuheng.service.LevelService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/content")
public class ContentController extends BaseController {
    private String PREFIX = "/modular/shuheng/job/";

    @Autowired
    private LevelService levelService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private DataService dataService;

    @RequestMapping("/cityContent")
    public String cityContent(@RequestParam(value = "levelId",required = false)String levelId,Model model){
        if(ToolUtil.isOneEmpty(levelId)){
            throw new RequestEmptyException();
        }
        Level level = levelService.getById(levelId);
        model.addAttribute("level",level);
        return PREFIX + "city_content.html";
    }


    @RequestMapping("/countyContent")
    public String countyContent(@RequestParam(value = "levelId",required = false)String levelId,Model model){
        if(ToolUtil.isOneEmpty(levelId)){
            throw new RequestEmptyException();
        }
        Level level = levelService.getById(levelId);
        model.addAttribute("level",level);
        return PREFIX + "county_content.html";
    }


    @RequestMapping(value = "/edit")
    @ResponseBody
    @Transactional
    public ResponseData edit(@RequestParam(value = "levelId",required = false)String levelId,
                            @RequestParam(value = "regionType",required = false)String regionType,
            @RequestParam(value = "contentJson",required = false)String contentJson) {
        if (ToolUtil.isOneEmpty(levelId,contentJson)) {
            throw new RequestEmptyException();
        }

        JSONArray array = JSONArray.parseArray(contentJson);
        List<Data> dataList = new ArrayList<>();
        for(int i=0;i<array.size(); i++){
            JSONObject contentObj = array.getJSONObject(i);
            String cVal = contentObj.getString("content");
            Content content = new Content();
            //把content更新成空的情况
            if(ToolUtil.isEmpty(cVal) && ToolUtil.isNotEmpty(contentObj.getString("contentId"))){
                //此时删除content就可以了
                contentService.removeById(contentObj.getString("contentId"));
            }
            if(StringUtils.isNotBlank(cVal)){
                if(ToolUtil.isNotEmpty(contentObj.getString("contentId"))){
                    content.setContentId(contentObj.getLong("contentId"));
                }
                content.setContentId(contentObj.getLong("contentId"));
                content.setContent(contentObj.getString("content"));
                content.setLevelId(contentObj.getLong("levelId"));
                content.setRegionType(contentObj.getInteger("regionType"));
                content.setSort(contentObj.getInteger("order"));
                content.setYear(contentObj.getInteger("year"));
                contentService.saveOrUpdate(content);
            }
            JSONArray dataArr = contentObj.getJSONArray("datas");
            for(int j=0;j<dataArr.size();j++){
                Data data = new Data();
                JSONObject dataObj = dataArr.getJSONObject(j);
                if(ToolUtil.isNotEmpty(dataObj.getString("dataId"))){
                    data.setDataId(dataObj.getLong("dataId"));
                }
                data.setDataName(dataObj.getString("dataName"));
                data.setDataType(dataObj.getString("dataType"));
                data.setDataYear(dataObj.getInteger("dataYear"));
                data.setDataMonth(dataObj.getInteger("dataMonth"));
                data.setDataScore(dataObj.getBigDecimal("dataScore"));
                data.setBaseScore(dataObj.getBigDecimal("baseScore"));
                data.setRegionType(dataObj.getInteger("regionType"));
                data.setDataType(dataObj.getString("dataType"));
                data.setSort(dataObj.getInteger("sort"));
                data.setDeptId(dataObj.getLong("dept"));
                if(StringUtils.isNotEmpty(content.getContent())){
                    //有内容区分才设置内容id，否则直接挂在阶段下边
                    data.setContentId(content.getContentId());
                    data.setLevelId(null);
                }else{
                    data.setLevelId(Long.parseLong(levelId));
                    data.setContentId(null);
                }
                dataList.add(data);
            }

        }
        dataService.saveOrUpdateBatch(dataList);
        return SUCCESS_TIP;
    }

    /**
     * 根据阶段id查询内容
     * 区分市级和区县级
     * @param levelId
     * @param regionType
     * @return
     */
    @RequestMapping("/listContentByLevelId")
    @ResponseBody
    public Object listContentByLevelId(@RequestParam(value = "levelId",required = false)String levelId,
                                       @RequestParam(value = "regionType",required = false)String regionType){
        if(ToolUtil.isOneEmpty(levelId,regionType)){
            throw new RequestEmptyException();
        }
        List<Content> list = contentService.listContentByLevelId(levelId,regionType);
        if(list!=null && list.size()>0){
            for(int i=0;i<list.size();i++){
                List<Data> dataList = dataService.listByContentId(list.get(i).getContentId(),regionType);
                list.get(i).setDataList(dataList);
            }
        }

        List<Data> dataList = dataService.listByLevelId(levelId,regionType);
        if(dataList!=null && dataList.size()>0){
            Content content = new Content();
            content.setContent("");
            content.setDataList(dataList);
            if(list==null){
                list = new ArrayList<>();
                list.add(content);
            }else{
                list.add(content);
            }
        }
        return list;
    }

    /**
     * 删除内容，并删除内容下的data
     * @param contentId
     * @return
     */
    @RequestMapping(value = "/deleteContent")
    @ResponseBody
    public ResponseData deleteContent(@RequestParam(value = "contentId",required = false)Long contentId,
                                      @RequestParam(value = "levelId",required = false)Long levelId){
        if(ToolUtil.isNotEmpty(contentId)){
            contentService.removeById(contentId);

            //删除data
            QueryWrapper<Data> wrapper = new QueryWrapper<>();
            wrapper.eq("content_id",contentId);
            dataService.remove(wrapper);
        }else{
            QueryWrapper<Data> wrapper = new QueryWrapper<>();
            wrapper.eq("level_id",levelId);
            dataService.remove(wrapper);
        }
        return SUCCESS_TIP;
    }

    /**
     * 删除data
     * @param dataId
     * @return
     */
    @RequestMapping(value = "/deleteData")
    @ResponseBody
    public ResponseData deleteData(@RequestParam(value = "dataId",required = false)Long dataId){
        if(ToolUtil.isEmpty(dataId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        dataService.removeById(dataId);
        return SUCCESS_TIP;
    }

}
